package demo.spring.securing;

import demo.spring.securing.manager.CustomUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by lushun.chen on 2017/3/22.
 *
 * @author lushun.chen
 */
@Configuration
public class WebSecuringAdaptor extends WebSecurityConfigurerAdapter {
    private static Logger logger = LoggerFactory.getLogger(WebSecuringAdaptor.class);


    @Autowired
    private SecuritySettings securitySettings;

//    /**
//     * 添加白名单
//     *
//     * @param web
//     * @throws Exception
//     */
//    @Override
//    public void init(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers("/hello");
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                .anyRequest().authenticated()
//                .and()
//                .formLogin()
//                .loginPage("/login")
//                .permitAll();
        http.formLogin().loginPage("/login").permitAll().successHandler(loginSuccessHandler())
                .and().authorizeRequests()
                .antMatchers("/images/**", "/checkout", "script/**", "style/**").permitAll()
                .antMatchers(securitySettings.getPermitall().split(",")).permitAll()
                .anyRequest().authenticated()
                .and().csrf().requireCsrfProtectionMatcher(csrfSecurityRequestMatcher())
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and().logout().logoutSuccessUrl(securitySettings.getLogoutsuccessurl())
                .and().exceptionHandling().accessDeniedPage(securitySettings.getDeniedpage())
                .and().rememberMe().tokenValiditySeconds(1209600).tokenRepository(tokenRepository());

    }

    private PersistentTokenRepository tokenRepository() {
        return null;
    }

    private RequestMatcher csrfSecurityRequestMatcher() {
        return null;
    }

    //登陆成功处理器
    private AuthenticationSuccessHandler loginSuccessHandler() {
        AuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
                    throws ServletException, IOException {
                User user = (User) authentication.getPrincipal();
                logger.info("登陆用户user:" + user.getName() + "login:" + request.getContextPath());
                logger.info("IP:" + request.getRequestURI());
                super.onAuthenticationSuccess(request, response, authentication);
            }
        };
        return handler;
    }

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    public void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        // auth.userDetailsService(customUserDetailsService).passwordEncoder();
    }


}
